package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {
    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;

    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        serviceItem.setCreateTime(new Date());
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        ServiceItem temp = this.get(serviceItem.getId());
        if(ServiceItem.AUDITSTATUS_AUDITING.equals(temp.getAuditStatus())){
            throw new BusinessException("服务项目正在审核中,不可修改");
        }else if(ServiceItem.SALESTATUS_ON.equals(temp.getSaleStatus())){
            throw new BusinessException("上架服务项目不能修改，请下架后再修改");
        }
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void saleOn(Long id) {
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(id);
        if (serviceItem == null || ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())) {
            throw new BusinessException("参数异常");
        }
        if (ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())) {
            serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_ON);
            return;
        }else {
            if(ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())){
                serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_ON);
                return;
            } else{
                throw new BusinessException("只有在审核通过的情况下才允许上架");
            }
        }
    }

    @Override
    public void saleOff(Long id) {
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(id);
        if (serviceItem == null || ServiceItem.SALESTATUS_OFF.equals(serviceItem.getSaleStatus())) {
            throw new BusinessException("参数异常");
        }
        serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_OFF);
    }

    @Override
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {
        //判断审核满足条件
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(id);
        if (serviceItem == null || ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())
                || !ServiceItem.AUDITSTATUS_INIT.equals(serviceItem.getAuditStatus())) {
            throw new BusinessException("参数异常");
        }
        //套餐审核记录信息-业务线
        CarPackageAudit audit = new CarPackageAudit();
        if (director == null){
            throw new BusinessException("必须指定第一审核人为店长");
        }
        audit.setAuditorId(director);
        audit.setBpmnInfoId(bpmnInfoId);
        audit.setCreateTime(new Date());
        audit.setCreator(ShiroUtils.getUser().getUserName());
        audit.setInfo(info);
        audit.setServiceItemId(id);
        audit.setServiceItemInfo(serviceItem.getInfo());
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
        audit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);

        carPackageAuditService.save(audit);
        //服务单项状态-审核中
        serviceItemMapper.changeAuditStatus(id,ServiceItem.AUDITSTATUS_AUDITING);
        //启动流程-流程线
        //--设置审核参数--审核人--审核价格
        Map<String, Object> map = new HashMap<>();
        map.put("director",director);
        if (finance != null){
            map.put("finance",finance);
        }
        //activit7操作时判断不支持 BigDecimal
        map.put("discountPrice",serviceItem.getDiscountPrice().longValue());
        //--设置businessKey
        String businessKey = audit.getId().toString();

        //获取流程
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);

        //使用businessKey 将业务线与流程线绑定
        //1:启动key  2:businessKey  3:流程图中各种参设置
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(bpmnInfo.getActProcessKey(), businessKey, map);

        //更新启动审核流程对象id到套餐审核记录表中
        carPackageAuditService.updateInstanceId(audit.getId(),instance.getId());
    }

    @Override
    public void changeAuditStatus(Long id, Integer status) {
        serviceItemMapper.changeAuditStatus(id, status);
    }
}
